package com.cskaoyan.batch;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 创建日期: 2021/11/23 16:25
 *
 * @author ciggar
 * 循环来处理
 */
public class BatchDemo1 {

    // 获取连接
    static Connection connection;
    static {
        connection = JDBCUtils.getConnection();
    }


    public static void main(String[] args) throws SQLException {

//        long t1 = System.currentTimeMillis();
//        batchForeach();
//        long t2 = System.currentTimeMillis();
//        batchUseStatement();
        long t3 = System.currentTimeMillis();
        batchUsePrepareStatement();
        long t4 = System.currentTimeMillis();

//        System.out.println("for循环的时间：" + (t2-t1) + " ms");
//        System.out.println("statement批处理的时间：" + (t3-t2) + " ms");
        System.out.println("prepapreStatement批处理的时间：" + (t4-t3) + " ms");

        connection.close();


    }

    // 循环来处理
    public static void batchForeach() throws SQLException {


        // 获取statement对象
        Statement statement = connection.createStatement();

        for (int i = 0; i < 1000; i++) {
            // 执行SQL语句
            statement.executeUpdate("insert into user values (null,'张飞','俺也一样','哥哥救我')");
        }

        // 关闭资源
        JDBCUtils.closeReources(null,statement,null);

    }

    // statement
    public static void batchUseStatement() throws SQLException {

        // 获取连接
        Connection connection = JDBCUtils.getConnection();

        // 获取statement对象
        Statement statement = connection.createStatement();

        for (int i = 0; i < 1000; i++) {
            statement.addBatch("insert into user values (null,'武松','喝酒打老虎','嫂嫂自重')");
        }

        statement.executeBatch();

        // 关闭资源
        JDBCUtils.closeReources(null,statement,null);



    }

    // prepareStatement
    public static void batchUsePrepareStatement() throws SQLException {

        // 获取连接
        Connection connection = JDBCUtils.getConnection();

        // 获取PrepareStatement对象
        PreparedStatement preparedStatement = connection.prepareStatement("insert into user values (null,?,?,?)");

        for (int i = 0; i < 100000; i++) {

            preparedStatement.setString(1,"猪八戒");
            preparedStatement.setString(2,"嫦娥");
            preparedStatement.setString(3,"大师兄，妖怪被师傅抓走了");

            // 添加到批处理
            preparedStatement.addBatch();

        }

        // 执行批处理
        preparedStatement.executeBatch();


        // 关闭资源
        JDBCUtils.closeReources(null,preparedStatement,null);

    }

}
